package com.linkwechat.quartz.task;

import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.enums.MediaType;
import com.linkwechat.common.tenant.TenantContextHolder;
import com.linkwechat.quartz.component.WeCorpAccountComponent2;
import com.linkwechat.wecom.client.EsbClient;
import com.linkwechat.wecom.client.WeKfClient;
import com.linkwechat.wecom.domain.*;
import com.linkwechat.wecom.domain.dto.WeMediaDto;
import com.linkwechat.wecom.domain.dto.WeResultDto;
import com.linkwechat.wecom.domain.dto.kf.*;
import com.linkwechat.wecom.mapper.*;
import com.linkwechat.wecom.service.IWeAccessTokenService;
import com.linkwechat.wecom.service.IWeMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by Administrator on 2022-5-11.
 */

@Slf4j
@Component("WeworkKfAccountSyncTask")
public class WeworkKfAccountSyncTask {
    @Autowired
    EsbClient esbClient;

    @Autowired
    WeKfClient weKfClient;

    @Autowired
    private IWeAccessTokenService iWeAccessTokenService;

    @Autowired
    private IWeMaterialService materialService;

    @Resource
    WeworkKfAccountMapper weworkKfAccountMapper;

    @Resource
    WeCorpAccountMapper weCorpAccountMapper;

    @Resource
    WeUserMapper weUserMapper;

    @Resource
    WeworkKfMemberRelationMapper weworkMemberRelationMapper;

    @Resource
    WeworkKfServicerMapper weworkKfServicerMapper;

    @Resource
    WeworkKfCustomerMapper weworkKfCustomerMapper;

    @Resource
    WeworkKfRelationMapper weworkKfRelationMapper;

    @Resource
    WeworkKfLogMapper weworkKfLogMapper;

    @Resource(name="weCorpAccountComponent2")
    private WeCorpAccountComponent2 weCorpAccountComponent;

    private final int offset = 500;

//    @Override
//    public WeworkKfAccount clone() throws CloneNotSupportedException{
//        //浅拷贝
//        return (WeworkKfAccount)super.clone();
//    }

    public void syncWeworkKfAccount() {
        log.info("商家客服账号同步>>>>>>>>>>>>>>>>>>>启动");

        try {
            //上传客服账号头像
            WeMediaDto mediaDto = materialService.uploadTemporaryMaterial("https://wwcdn.weixin.qq.com/node/wework/images/kf_head_image_url_2.png", MediaType.IMAGE.getMediaType(), "临时文件");

            //接口返回实体
            AddAccountDto addAccountDto = new AddAccountDto();
            AddAccountResDto addAccountResDto;
            AddContactWayDto addContactWayDto = new AddContactWayDto();
            AddContactWayResDto addContactWayResDto;

            //获取企业信息
//            QueryWrapper<WeCorpAccount> wrapperWeCorpAccount = new QueryWrapper<>();
//            wrapperWeCorpAccount.eq("tenant_code", TenantContextHolder.getTenantCode());
            WeCorpAccount weCorpAccount = weCorpAccountMapper.selectOne(null);

            //重置客服账号状态
            WeworkKfAccount weworkKfAccount =new WeworkKfAccount();
            //weworkKfAccount.setTenantCode(TenantContextHolder.getTenantCode());
            weworkKfAccountMapper.resetSyncFlag(weworkKfAccount);

            //根据租户获取对应所属商户
            WeKfCompanyDto weKfCompanyDto = new WeKfCompanyDto();
            WeKfSyncContactWayDto weKfSyncContactWayDto = new WeKfSyncContactWayDto();
            weKfCompanyDto.setScrmTenantCode(TenantContextHolder.getTenantCode());
            List<WeKfCompanyResDto> weKfCompanyResDtos = esbClient.syncKfAccount(weKfCompanyDto);
            if(weKfCompanyResDtos.size()>0) {
                Map openKfidOld = new HashMap<>();
                OpenKfidDto openKfidDto = new OpenKfidDto();

                for (WeKfCompanyResDto w : weKfCompanyResDtos) {
                    //客服账号名称
                    String kfAccountName;
                    if (w.getCompanyName().length() > 16) {    //账号名称不能超过16
                        kfAccountName = w.getCompanyName().substring(0, 16);
                    } else {
                        kfAccountName = w.getCompanyName();
                    }

                    weworkKfAccount.setScene(w.getCompanyId().toString());
                    List<WeworkKfAccount> weworkKfAccounts = weworkKfAccountMapper.selectByScene(weworkKfAccount);
                    if (weworkKfAccounts.size() == 0 || weworkKfAccounts.get(0).getState() == 0) {
                        if (weworkKfAccounts.size() == 0) {
                            //注册客服账号
                            addAccountDto.setName(kfAccountName);
                            addAccountDto.setMedia_id(mediaDto.getMedia_id());
                            addAccountResDto = weKfClient.addAccount(addAccountDto);

                            //记录账号信息
                            weworkKfAccount.setOpenKfid(addAccountResDto.getOpenKfid());
                            weworkKfAccount.setKfAccountName(kfAccountName);
                            weworkKfAccount.setSyncFlag(1);
                            weworkKfAccount.setServiceNum(0);
                            weworkKfAccount.setCreateTime(new Date());
                            weworkKfAccountMapper.insertWeworkKfAccount(weworkKfAccount);

                        } else {
                            weworkKfAccount = weworkKfAccounts.get(0);

                            //删除原客服账号
                            openKfidDto.setOpen_kfid(weworkKfAccount.getOpenKfid());
                            WeResultDto weResultDto = weKfClient.delAccount(openKfidDto);

                            //注册客服账号
                            addAccountDto.setName(kfAccountName);
                            addAccountDto.setMedia_id(mediaDto.getMedia_id());
                            addAccountResDto = weKfClient.addAccount(addAccountDto);

                            //记录账号信息
                            openKfidOld.put("open_kfid", weworkKfAccount.getOpenKfid());    //记录原客服账号ID
                            weworkKfAccount.setOpenKfid(addAccountResDto.getOpenKfid());
                            weworkKfAccount.setKfAccountName(kfAccountName);
                            weworkKfAccount.setSyncFlag(1);
                            weworkKfAccountMapper.updateById(weworkKfAccount);

                            //重置所有数据表中的客服账号ID
                            //接待人员
                            List<WeworkKfServicer> weworkKfServicers = weworkKfServicerMapper.selectByMap(openKfidOld);
                            for(WeworkKfServicer w_old: weworkKfServicers) {
                                w_old.setOpenKfid(addAccountResDto.getOpenKfid());
                                weworkKfServicerMapper.updateById(w_old);
                            }

                            //咨询客户
                            List<WeworkKfCustomer> weworkKfCustomers = weworkKfCustomerMapper.selectByMap(openKfidOld);
                            for(WeworkKfCustomer w_old: weworkKfCustomers) {
                                w_old.setOpenKfid(addAccountResDto.getOpenKfid());
                                weworkKfCustomerMapper.updateById(w_old);
                            }

                            //客服客户关系
                            List<WeworkKfRelation> weworkKfRelations= weworkKfRelationMapper.selectByMap(openKfidOld);
                            for(WeworkKfRelation w_old: weworkKfRelations) {
                                w_old.setOpenKfid(addAccountResDto.getOpenKfid());
                                weworkKfRelationMapper.updateById(w_old);
                            }

                            //咨询日志
                            List<WeworkKfLog> weworkKfLogs = weworkKfLogMapper.selectByMap(openKfidOld);
                            for(WeworkKfLog w_old: weworkKfLogs) {
                                w_old.setOpenKfid(addAccountResDto.getOpenKfid());
                                weworkKfLogMapper.updateById(w_old);
                            }

                        }

                        //获取客服账号链接并记录
                        addContactWayDto.setOpen_kfid(addAccountResDto.getOpenKfid());
                        addContactWayDto.setScene(w.getCompanyId().toString());
                        addContactWayResDto = weKfClient.addContactWay(addContactWayDto);

                        //记录客服账号链接
                        weKfSyncContactWayDto.setCompanyId(w.getCompanyId());
                        weKfSyncContactWayDto.setKfUrl(addContactWayResDto.getUrl());
                        weKfSyncContactWayDto.setCorpId(weCorpAccount.getCorpId());
                        esbClient.syncContactWay(weKfSyncContactWayDto);

                    } else {
                        weworkKfAccount = weworkKfAccounts.get(0);
                        weworkKfAccount.setKfAccountName(kfAccountName);
                        weworkKfAccount.setSyncFlag(1);
                        weworkKfAccountMapper.updateById(weworkKfAccount);
                    }

                }

            }

            //将新的syncFlag更新到状态
            weworkKfAccountMapper.copySyncFlagToState(null);

            //删除未同步的客服账号




            //同步接待人员
            syncMemberAndWeworkUserRelation();

        } catch (Exception e) {
            e.printStackTrace();
        }

        log.info("商家客服账号同步>>>>>>>>>>>>>>>>>>>结束");

    }



    public void syncMemberAndWeworkUserRelation() {
        log.info("商家memberId与企微桥接同步>>>>>>>>>>>>>>>>>>>启动");

        try {
            WeUser weUser = new WeUser();
            List<WeUser> weUsers;
            WeworkKfMemberRelation weworkMemberRelation;

            WeKfTenantDto weKfTenantDto = new WeKfTenantDto();
            weKfTenantDto.setTenantCode(TenantContextHolder.getTenantCode());
            List<WeKfTenantResDto> weKfTenantResDtoList = esbClient.getMobileAndMemberByTenant(weKfTenantDto);
            if(weKfTenantResDtoList.size()>0) {
                //重置所有syncFlag
                weworkMemberRelationMapper.resetSyncFlag(null);

                //客服账号
                WeworkKfAccount weworkKfAccount =new WeworkKfAccount();
                ServicerListResDto servicerListResDto;

                //接待人员
                WeworkKfServicer weworkKfServicer = new WeworkKfServicer();
                ServicerDto servicerDto = new ServicerDto();

                //接待人员激活状态
                WekfKfActivate wekfKfActivate = new WekfKfActivate();

                for (WeKfTenantResDto w : weKfTenantResDtoList) {
                    //确认是否有客服账号
                    weworkKfAccount.setScene(w.getCompanyId().toString());
                    List<WeworkKfAccount> weworkKfAccounts = weworkKfAccountMapper.selectByScene(weworkKfAccount);
                    if (weworkKfAccounts.size() > 0 && weworkKfAccounts.get(0).getState()==1) {    //无客服账号或账号无效则直接跳过
                        weUser.setMobile(w.getMobile());
                        weUser.setIsActivate(1);
                        weUsers = weUserMapper.selectWeUserList(weUser);
                        if (weUsers.size() > 0) {
                            weworkMemberRelation = weworkMemberRelationMapper.selectByMemberId(w.getMemberId());
                            if (weworkMemberRelation == null) {
                                weworkMemberRelation = new WeworkKfMemberRelation();
                                weworkMemberRelation.setUserid(weUsers.get(0).getUserId());
                                weworkMemberRelation.setMemberId(w.getMemberId());
                                weworkMemberRelation.setSyncFlag(1);
                                weworkMemberRelationMapper.insert(weworkMemberRelation);

                                //添加接待人员
                                servicerDto.setOpen_kfid(weworkKfAccounts.get(0).getOpenKfid());
                                List<String> ul = new ArrayList<>();
                                ul.add(weUsers.get(0).getUserId());
                                servicerDto.setUserid_list(ul);
                                servicerListResDto = weKfClient.addServicer(servicerDto);

                                //新增成功
                                if (servicerListResDto.getErrcode() == 0) {    //失败直接跳过
                                    //同步接待人员激活状态至cloud_hrstaffinfo
                                    wekfKfActivate.setAdminId(w.getAdminId());
                                    wekfKfActivate.setMemberId(w.getMemberId());
                                    wekfKfActivate.setIsKfActivate(1);
                                    esbClient.updateKfActivateSeq(wekfKfActivate);

                                    weworkKfServicer = new WeworkKfServicer();
                                    weworkKfServicer.setUserid(weUsers.get(0).getUserId());
                                    weworkKfServicer.setOpenKfid(weworkKfAccounts.get(0).getOpenKfid());
                                    weworkKfServicer.setCreateTime(new Date());
                                    weworkKfServicer.setUpdateTime(new Date());
                                    weworkKfServicer.setStatus(1);
                                    weworkKfServicer.setIsActivate(1);
                                    weworkKfServicerMapper.insertWeworkKfServicer(weworkKfServicer);
                                }

                            } else {
                                weworkMemberRelation.setUserid(weUsers.get(0).getUserId());
                                weworkMemberRelation.setSyncFlag(1);
                                weworkMemberRelationMapper.updateById(weworkMemberRelation);

                                //判断接待人员状态是否激活
                                weworkKfServicer.setOpenKfid(weworkKfAccounts.get(0).getOpenKfid());
                                weworkKfServicer.setUserid(weUsers.get(0).getUserId());
                                List<WeworkKfServicer> weworkKfServicers = weworkKfServicerMapper.selectByUseridAndOpenKfid(weworkKfServicer);
                                if(weworkKfServicers.size()==0){
                                    //添加接待人员
                                    servicerDto.setOpen_kfid(weworkKfAccounts.get(0).getOpenKfid());
                                    List<String> ul = new ArrayList<>();
                                    ul.add(weUsers.get(0).getUserId());
                                    servicerDto.setUserid_list(ul);
                                    servicerListResDto = weKfClient.addServicer(servicerDto);

                                    //新增成功
                                    if (servicerListResDto.getErrcode() == 0) {    //失败直接跳过
                                        //同步接待人员激活状态至cloud_hrstaffinfo
                                        wekfKfActivate.setAdminId(w.getAdminId());
                                        wekfKfActivate.setMemberId(w.getMemberId());
                                        wekfKfActivate.setIsKfActivate(1);
                                        esbClient.updateKfActivateSeq(wekfKfActivate);

                                        weworkKfServicer = new WeworkKfServicer();
                                        weworkKfServicer.setUserid(weUsers.get(0).getUserId());
                                        weworkKfServicer.setOpenKfid(weworkKfAccounts.get(0).getOpenKfid());
                                        weworkKfServicer.setCreateTime(new Date());
                                        weworkKfServicer.setUpdateTime(new Date());
                                        weworkKfServicer.setStatus(1);
                                        weworkKfServicer.setIsActivate(1);
                                        weworkKfServicerMapper.insertWeworkKfServicer(weworkKfServicer);
                                    }

                                } else if(weworkKfServicers.get(0).getIsActivate()==0) {    //未激活
                                    //再次添加接待人员
                                    servicerDto.setOpen_kfid(weworkKfAccounts.get(0).getOpenKfid());
                                    List<String> ul = new ArrayList<>();
                                    ul.add(weUsers.get(0).getUserId());
                                    servicerDto.setUserid_list(ul);

                                    servicerListResDto = weKfClient.addServicer(servicerDto);
                                    //新增成功
                                    if (servicerListResDto.getErrcode() == 0) {    //失败直接跳过
                                        weworkKfServicer = weworkKfServicers.get(0);
                                        weworkKfServicer.setUpdateTime(new Date());
                                        weworkKfServicer.setIsActivate(1);
                                        weworkKfServicerMapper.insertWeworkKfServicer(weworkKfServicer);
                                    }

                                }

                            }

                        }

                    }

                }

                //将新的syncFlag更新到状态
                weworkMemberRelationMapper.copySyncFlagToState(null);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        log.info("商家memberId与企微桥接同步>>>>>>>>>>>>>>>>>>>结束");

    }

    public void delKfAccount(){


    }

}